# -*- coding: utf-8 -*-

# MIT License
#
# Copyright (c) 2017 Tijme Gommers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from collections import OrderedDict
from nyawc.http.Request import Request
from nyawc.http.Response import Response
from nyawc.QueueItem import QueueItem
from nyawc.helpers.MongoHelper import mongoUtil

class Queue(object):
    """A 'hash' queue containing all the requests of the crawler.

    Note:
        This queue uses a certain hash to prevent duplicate entries and improve
        the time complexity by checking if the hash exists instead of iterating
        over all items.

    Attributes:
        __options (:class:`nyawc.Options`): The options to use (used when generating queue item hashes).
        count_total (int): The total count of requests in the queue.
        items_queued list(:class:`nyawc.QueueItem`): The queued items (yet to be executed).
        items_in_progress list(:class:`nyawc.QueueItem`): The items currently being executed.
        items_finished list(:class:`nyawc.QueueItem`): The finished items.
        items_cancelled list(:class:`nyawc.QueueItem`): Items that were cancelled.
        items_errored list(:class:`nyawc.QueueItem`): Items that generated an error.

    """

    def __init__(self, host, options):
        """Constructs a Queue instance.

        Args:
            options (:class:`nyawc.Options`): The options to use.

        """

        self.__options = options
        self.count_total = 0
        self.host = host
        self.mongo = mongoUtil(self.host)
        '''
        self.items_queued = OrderedDict()
        self.items_in_progress = OrderedDict()
        self.items_finished = OrderedDict()
        self.items_cancelled = OrderedDict()
        self.items_errored = OrderedDict()
        for status in QueueItem.STATUSES:
            self.init_queue(status)
        '''

    def Data2Item(self, data, status=QueueItem.STATUS_QUEUED):
        request = Request()
        request.Dict2Req(data)
        queue_item = QueueItem(request, Response(request.url), status)
        return queue_item

    def get_queue(self, status=QueueItem.STATUS_QUEUED,find_one=False):
        items = OrderedDict()
        condition = {"status":status}
        data = self.mongo.mongo_find(condition,find_one)
        if not data:
            return
        for req in data:
            queue_item = self.Data2Item(req,status)
            hash_key = queue_item.get_hash()
            if hash_key not in items.keys():
                items[hash_key] = queue_item
        return list(items.items())[0][1] if find_one else items

    def add_request(self, request, status=QueueItem.STATUS_QUEUED, in_sql=False):
        """Add a request to the queue.

        Args:
            request (:class:`nyawc.http.Request`): The request to add.

        Returns:
            :class:`nyawc.QueueItem`: The created queue item.

        """

        queue_item = QueueItem(request, Response(request.url),status)
        if not in_sql and not self.has_request(request):
            self.mongo.mongo_save(request.Req2Dict(status,queue_item.get_hash()))
        self.count_total += 1
        return queue_item

    def has_request(self, request):
        """Check if the given request already exists in the queue.

        Args:
            request (:class:`nyawc.http.Request`): The request to check.

        Returns:
            bool: True if already exists, False otherwise.

        """

        queue_item = QueueItem(request, Response(request.url))
        key = queue_item.get_hash()

        if self.mongo.mongo_find({"hash": key}).count()>0:
            return True

        return False

    def move(self, queue_item, status):
        """Move a request/response pair to another status.

        Args:
            queue_item (:class:`nyawc.QueueItem`): The queue item to move
            status (str): The new status of the queue item.

        """
        key_hash = queue_item.get_hash()
        condition = {"hash": key_hash}
        data = {"status": status}
        self.mongo.mongo_update(condition, data)
        self.count_total -= 1

    def move_bulk(self, from_statuses, to_status):
        """Move a bulk of request/response pairs to another status

        Args:
            from_statuses list(str): The statuses to move from
            to_status (str): The status to move to

        """
        for status in from_statuses:
            queue_all = self.get_all(status)
            for items in queue_all:
                self.move(queue_all[items], to_status)

    def get_first(self, status):
        """Get the first item in the queue that has the given status.

        Args:
            status (str): return the first item with this status.

        Returns:
            :class:`nyawc.QueueItem`: The first queue item with the given status.

        """
        return self.get_queue(status,True)

    def get_all(self, status):
        """Get all the items in the queue that have the given status.

        Args:
            status (str): return the items with this status.

        Returns:
            list(:class:`nyawc.QueueItem`): All the queue items with the given status.

        """

        return self.get_queue(status)

    def get_all_count(self, status):
        condition = {"status":status}
        return self.mongo.mongo_find(condition).count()

    def __set_var(self, name, value):
        """Set an instance/class var by name.

        Args:
            name (str): The name of the variable.
            value (obj): I'ts new value.

        """

        setattr(self, name, value)

    def __get_var(self, name):
        """Get an instance/class var by name.

        Args:
            name (str): The name of the variable.

        Returns:
            obj: I'ts value.

        """

        return getattr(self, name)
